#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> 
 
#define SERVER_PORT    5555


int main(int argc, char **argv)
{
    int server_fd;
    int accept_fd;

    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(0 > server_fd) {
        perror("socket error");
        exit(-1);
    }

    struct sockaddr_in server_addr = {0};
    struct sockaddr_in client_addr = {0};
    struct in_addr addr; 
    char ip_str[20] = {0}; 
    int addrlen = sizeof(client_addr); 
    char recvbuf[512];
 
    //填充变量 
    server_addr.sin_family = AF_INET;  
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    server_addr.sin_port = htons(SERVER_PORT);//端口号 
    //将地址与套接字进行关联、绑定 
    if(0 > bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr))) {
        perror("bind error"); 
        close(server_fd); 
        exit(-1);
    }
    inet_ntop(AF_INET, &server_addr.sin_addr.s_addr, ip_str, sizeof(ip_str)); 
    printf("服务端主机的IP地址: %s\n", ip_str); 
    printf("服务端进程的端口号: %d\n\n", server_addr.sin_port); 

    //使服务器进入监听状态
    if(0 > listen(server_fd,50)) {
        perror("listen error"); 
        close(server_fd); 
        exit(-1);
    }

    //阻塞等待客户端连接  
    accept_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addrlen);
    if (0 > accept_fd) { 
        perror("accept error"); 
        close(server_fd); 
        exit(-1); 
    } 

    //退出阻塞状态，代表有客户端连接
    printf("有客户端接入...\n"); 
    inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_str, sizeof(ip_str)); 
    printf("客户端主机的IP地址: %s\n", ip_str); 
    printf("客户端进程的端口号: %d\n", client_addr.sin_port); 

    for(; ;) {
        //接收缓冲区清零
        memset(recvbuf, 0x00, sizeof(recvbuf));
        
        //读取数据
        if(0 > recv(accept_fd, recvbuf, sizeof(recvbuf), 0)) {
            perror("recv error"); 
            close(accept_fd); 
            break; 
        }

        // 将读取到的数据以字符串形式打印出来 
        printf("from client: %s\n", recvbuf); 

        // 如果读取到"exit"则关闭套接字退出程序 
        if (0 == strncmp("exit", recvbuf, 4)) { 
            printf("server exit...\n"); 
            close(accept_fd); 
            break; 
        } 
    }

    close(server_fd);
    exit(0);
}